<template>
  <div class="login" v-if="loginBoxState">
    <div class="modal in" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close" @click="handleLoginBoxClose()">
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title" id="myModalLabel">{{loginTypeState==1?'登录':'注册'}}</h4>
          </div>
          <div class="modal-body">
            <div class="form-horizontal">
              <div class="form-group">
                <label for="" class="col-sm-3 control-label">手机号：</label>
                <div class="col-sm-5">
                  <input type="text" class="form-control" v-model="mobile">
                </div>
              </div>
              <div class="form-group">
                <label for="" class="col-sm-3 control-label">密码：</label>
                <div class="col-sm-5">
                  <input type="password" class="form-control" v-model="password">
                </div>
              </div>
              <template v-if="loginTypeState==2">
                <div class="form-group">
                  <label for="" class="col-sm-3 control-label">确认密码：</label>
                  <div class="col-sm-5">
                    <input type="password" class="form-control" v-model="password1">
                  </div>
                </div>
                <div class="form-group">
                  <label for="" class="col-sm-3 control-label">昵称：</label>
                  <div class="col-sm-5">
                    <input type="text" class="form-control" v-model="nickname">
                  </div>
                </div>
                <div class="form-group">
                  <label for="" class="col-sm-3 control-label">性别：</label>
                  <div class="col-sm-3">
                    <select name="" id="" class="form-control" v-model="usersex">
                      <option value="1">男</option>
                      <option value="2">女</option>
                    </select>
                  </div>
                </div>
                <div class="form-group">
                  <label for="" class="col-sm-3 control-label">验证码：</label>
                  <div class="col-sm-3">
                    <input type="text" class="form-control" v-model="yzcode">
                  </div>
                  <div class="col-sm-3">
                    <button class="btn btn-default" disabled v-if="countdown<60">{{countdown}}s</button>
                    <button class="btn btn-default" v-else @click="handleSendCode()">发送验证码</button>
                  </div>
                </div>
                <!-- <div class="form-group">
                  <label for="" class="col-sm-3 control-label">头像：</label>
                  <div class="col-sm-3">
                    <button class="btn btn-default" @change='selectFile'>
                    上传头像
                      <input type="file" name="file" class="up-input" />
                    </button>
                  </div>
                </div> -->
              </template>
            </div>
          </div>
          <div class="modal-footer">
            <template v-if="loginTypeState==1">
              <a href="javascript:;" class="pull-left footer-link" @click="handleLoginTypeChange(2)">
                <u>去注册</u>
              </a>
            </template>
            <template v-else>
              <a href="javascript:;" class="pull-left footer-link" @click="handleLoginTypeChange(1)">
                <u>去登录</u>
              </a>
            </template>
            <template v-if="loginTypeState==1">
              <button type="button" class="btn btn-ghost" @click="handleLogin()">登录</button>
            </template>
            <template v-else>
              <button type="button" class="btn btn-ghost" @click="handleRegist()">注册</button>
            </template>

          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import qs from 'qs'
import Cookies from 'js-cookie'
export default {
  name: 'common-login',
  data() {
    return {
      mobile: '',
      password: '',
      password1: '',
      nickname: '',
      usersex: '1',
      yzcode: '',
      headimg: '',
      option: {
        img: '',
        size: '',
        outputType: 'jpeg'
      },
      countdown: 60,
      countTimer: null
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo
    },
    loginTypeState() {
      return this.$store.state.loginTypeState
    },
    loginBoxState() {
      return this.$store.state.loginBoxState
    }
  },
  methods: {
    // 选择文件
    selectFile(e) {
      console.log(e)
      this.headimg = e.target.files
    },
    handleLoginBoxClose() {
      this.$store.dispatch('handleLoginBoxChange', false)
      if (!this.userInfo && this.$route.matched[0].name == 'my')
        this.$router.push({ path: '/index' })
      else if (this.$route.name == 'video-show') window.close()
    },
    handleLoginTypeChange(type) {
      this.$store.dispatch('handleLoginTypeChange', type)
    },
    handleSendCode() {
      let that = this
      var myreg = /^[1][3,4,5,7,8][0-9]{9}$/
      if (!myreg.test(that.mobile)) {
        alert('手机号输入错误')
      } else {
        axios
          .post('/user/sendCode', qs.stringify({ mobile: that.mobile }))
          .then(function(response) {
            if (response.data.suc == 200) {
              that.handleCodeTime()
            } else {
              if (response.data.errCode == 'ERROR_CODE_100001')
                alert('当前手机号码已经注册')
              else if (response.data.errCode == 'ERROR_CODE_000001')
                alert('短信发送失败')
              else if (response.data.errCode == 'ERROR_CODE_100002')
                alert('请过一分钟在尝试')
              else if (response.data.errCode == 'ERROR_CODE_100003')
                alert('一天最多发送5条短信')
            }
          })
          .catch(function(error) {
            console.log(error)
          })
      }
    },
    handleCodeTime() {
      //发送验证码倒计时
      let countdown = this.countdown
      let that = this
      if (countdown == 0) {
        countdown = 60
        clearTimeout(this.countTimer)
        return
      } else {
        countdown--
      }
      this.countTimer = setTimeout(function() {
        that.handleCodeTime(obj)
      }, 1000)
    },
    handleLogin() {
      let that = this
      let validateRule = [
        {
          vKind: this.mobile,
          vMes: '手机号不能为空'
        },
        {
          vKind: this.password,
          vMes: '密码不能为空'
        }
      ]
      if (!this.validate(validateRule)) {
        return
      }
      axios
        .post(
          '/user/login',
          qs.stringify({
            mobile: that.mobile,
            password: that.password
          })
        )
        .then(function(response) {
          if (response.data.suc == 200) {
            that.handleLoginBoxClose()
            that.$store.dispatch('handleUserInfoChange', response.data.data)
            Cookies.set(
              'userinfo',
              JSON.stringify({
                nickname: response.data.data.nickname,
                headimg: response.data.data.headimg,
                uid: response.data.data.id
              })
            )
            location.reload()
          } else if (response.data.errCode == 'ERROR_CODE_000002') {
            alert('手机号或密码错误')
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    validate(...val) {
      for (let i = 0; i < val[0].length; i++) {
        const ele = val[0][i]
        if (!ele['vKind']) {
          alert(ele['vMes'])
          break
        } else if (i === val[0].length - 1) {
          return true
        }
      }
    },
    handleRegist() {
      let that = this
      let validateRule = [
        {
          vKind: this.mobile,
          vMes: '手机号不能为空'
        },
        {
          vKind: this.password,
          vMes: '密码不能为空'
        },
        {
          vKind: this.password1,
          vMes: '请确认密码不能为空'
        },
        {
          vKind: this.nickname,
          vMes: ' 昵称不能为空'
        },
        {
          vKind: this.usersex,
          vMes: '性别不能为空'
        },
        {
          vKind: this.yzcode,
          vMes: '验证码不能为空'
        }
      ]
      if (!this.validate(validateRule)) {
        return
      }
      if (this.password != this.password1) {
        alert('两次密码输入不一致')
        return false
      }
      axios
        .post(
          '/user/regist',
          qs.stringify({
            nickName: that.nickname,
            mobile: that.mobile,
            code: that.yzcode,
            password: that.password,
            headimg:
              'https://kegonghui.oss-cn-beijing.aliyuncs.com/head/default.png'
          })
        )
        .then(function(response) {
          if (response.data.suc == 200) {
            alert('注册成功')
            that.handleLoginBoxClose()
            that.$store.dispatch('handleUserInfoChange', response.data.data)
            Cookies.set(
              'userinfo',
              JSON.stringify({
                nickname: response.data.data.nickname,
                headimg: response.data.data.headimg,
                uid: response.data.data.id
              })
            )
            location.reload()
          } else if (response.data.errCode == 'ERROR_CODE_100004') {
            alert('验证码输入错误')
          } else if (response.data.errCode == 'ERROR_CODE_100001') {
            alert('手机号码已经被使用')
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 100;
  .footer-link {
    margin-top: 5px;
  }
}
</style>
